package com.xuecheng.search.listener;

import com.xuecheng.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 1.交给容器管理
 * 2.配置方法，方法没有返回值，参数类型和消息一致
 * 3.在方法上配置注解
 */
@Slf4j
@Component
public class MessageListener {

    @Autowired
    SearchService searchService;
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "course.index.queue"
                    ),
                    exchange = @Exchange(
                            value = "content-exchange-one",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "course.pub"
            )
    )
    public void updateIndex (Long coursePubId) {
        log.info("获取到课程发布消息id={}",coursePubId);
        //更新es的索引
        try {
            searchService.createIndex(coursePubId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "course.delete.queue"
                    ),
                    exchange = @Exchange(
                            value = "content-exchange-two",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "course.delete"
            )
    )
    public void deleteIndex (Long coursePubId) {
        log.info("获取到课程删除消息id={}",coursePubId);
        try {
            searchService.deleteIndex(coursePubId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
